<!-- eslint-disable vue/valid-v-slot -->
<!-- 产品明细控件 -->
<template>
  <a-space direction="vertical" style="width: 100%">
    <div class="add-td" style="text-align: right">
      <a-space>
        <a-button
          type="primary"
          v-if="props.props.state === 4"
          :disabled="isBatchBuildTask"
          @click="batchBuildTask"
          >采购任务</a-button
        >
        <a-button
          type="primary"
          status="success"
          v-if="props.props.state === 4"
          :disabled="isBatchBuildOrder"
          @click="batchBuildOrder"
          >采购订单</a-button
        >
        <a-button
          type="text"
          v-if="props.props.state !== 4"
          @click="addTd"
          :disabled="props.disabled"
          >添加</a-button
        >
      </a-space>
    </div>

    <a-table
      row-key="id"
      :row-selection="disabled ? rowSelection : false"
      v-model:selectedKeys="selectedKeys"
      @select="onSelect"
      @select-all="onSelectAll"
      :data="data"
      :pagination="false"
    >
      <template #columns>
        <a-table-column :width="80" align="center">
          <template #title> 序号 </template>
          <template #tr> </template>
          <template #cell="{ rowIndex }">
            <div style="position: relative">
              <div>{{ rowIndex + 1 }}</div>
              <!-- <div
                v-if="!props.disabled"
                style="position: absolute; top: 7px; right: 30px"
                @click="addNewProduct(record, rowIndex)"
              >
                <icon-plus />
              </div> -->
            </div>
          </template>
        </a-table-column>
        <a-table-column title="产品编码" :width="100" align="center"
          ><template #cell="{ record }">
            <a-input disabled v-model="record.number" /> </template
        ></a-table-column>
        <a-table-column title="产品名称" :width="100" align="center"
          ><template #cell="{ record }">
            <a-input disabled v-model="record.name" /> </template
        ></a-table-column>
        <a-table-column title="产品规格" :width="100" align="center"
          ><template #cell="{ record }">
            <a-input disabled v-model="record.spec" /> </template
        ></a-table-column>
        <a-table-column title="基本单位" :width="100" align="center"
          ><template #cell="{ record }">
            <a-input disabled v-model="record.basicName" /> </template
        ></a-table-column>
        <a-table-column title="计划采购数量" :width="100" align="center"
          ><template #cell="{ record }">
            <a-input-number
              :min="1"
              :disabled="props.disabled"
              v-model="record.planAmount"
            /> </template
        ></a-table-column>
        <a-table-column title="实际数量" :width="100" align="center"
          ><template #cell="{ record }">
            <a-input disabled v-model="record.amount" /> </template
        ></a-table-column>

        <a-table-column :width="200" align="center">
          <template #title> 状态 </template>
          <template #cell="{ record }">
            <a-typography-text disabled v-if="record.state === 1">
              待创建
            </a-typography-text>
            <a-typography-text type="primary" v-if="record.state === 2">
              执行中
            </a-typography-text>
            <a-typography-text type="success" v-if="record.state === 3">
              已完成
            </a-typography-text>
            <a-typography-text type="warning" v-if="record.state === 4">
              异常完成
            </a-typography-text>
          </template>
        </a-table-column>
        <a-table-column fixed="right" :width="210" align="center">
          <template #title> 操作 </template>
          <template #cell="{ record, rowIndex }">
            <a-space>
              <a-popconfirm
                v-if="!props.props.state"
                content="是否要删除?"
                @ok="delItem(record, rowIndex)"
                type="error"
              >
                <a-button type="text" status="danger" :disabled="props.disabled"
                  >删除</a-button
                >
              </a-popconfirm>
              <a-button
                v-if="props.props.state === 4"
                :disabled="record.state === 2"
                type="text"
                @click="buildSingleTask(record)"
                >创建任务</a-button
              >
              <a-button
                v-if="props.props.state === 4"
                :disabled="record.state === 2"
                type="text"
                @click="See(record)"
                >创建订单</a-button
              >
            </a-space>
          </template>
        </a-table-column>
      </template>
    </a-table>
  </a-space>

  <a-modal
    v-if="visible"
    width="50%"
    v-model:visible="visible"
    @ok="handleOk"
    @cancel="searchHandleCancel"
    :mask-closable="false"
  >
    <template #title> 物料产品选择 </template>
    <div class="container">
      <div class="content">
        <a-space :size="30">
          <div style="display: flex">
            <a-space>
              <a-input-search
                v-model="nameVal"
                placeholder="请输入物料名称"
                search-button
                @search="search"
              />
            </a-space>
          </div>
          <div>
            <a-space>
              <a-button type="primary" @click="search">
                <template #icon> <icon-search /> </template>搜索</a-button
              >
              <a-button type="outline" @click="reset">
                <template #icon> <icon-refresh /> </template>重置</a-button
              >
            </a-space>
          </div>
        </a-space>
      </div>
      <tableTurn
        style="margin-top: 20px"
        :table-data="getMaterialData"
        ref="tableRef"
        :args="args"
      >
        <a-table-column :width="80" align="center">
          <template #title> 序号 </template>
          <template #cell="{ rowIndex }">
            {{ rowIndex + 1 }}
          </template>
        </a-table-column>
        <a-table-column
          align="center"
          :width="100"
          title="产品编号"
          data-index="number"
          :ellipsis="true"
          :tooltip="{
            position: 'top',
          }"
        >
        </a-table-column>
        <a-table-column
          align="center"
          :width="100"
          title="产品名称"
          data-index="name"
          :ellipsis="true"
          :tooltip="{
            position: 'top',
          }"
        >
        </a-table-column>
        <a-table-column
          align="center"
          :width="100"
          title="采购类别"
          data-index="materialName"
          :ellipsis="true"
          :tooltip="{
            position: 'top',
          }"
        >
        </a-table-column>
        <a-table-column
          align="center"
          title="规格型号"
          data-index="spec"
          :width="100"
          :ellipsis="true"
          :tooltip="{
            position: 'top',
          }"
        >
        </a-table-column>
        <!-- <a-table-column
            align="center"
            title="采购单位"
            data-index="basicUnitName"
            :width="100"
          >
          </a-table-column> -->
        <a-table-column
          align="center"
          title="需求交付日期"
          :width="100"
          :ellipsis="true"
          :tooltip="{
            position: 'top',
          }"
        >
          <template #cell="{ record }">
            {{ dayjs(record.deliveryTime).format('YYYY-MM-DD') }}
          </template>
        </a-table-column>
        <a-table-column
          align="center"
          title="申请人"
          data-index="applyByUserName"
          :width="100"
          :ellipsis="true"
          :tooltip="{
            position: 'top',
          }"
        >
        </a-table-column>
        <a-table-column
          align="center"
          title="申请日期"
          :width="100"
          :ellipsis="true"
          :tooltip="{
            position: 'top',
          }"
        >
          <template #cell="{ record }">
            {{ dayjs(record.applicationTime).format('YYYY-MM-DD') }}
          </template>
        </a-table-column>

        <a-table-column align="center" :width="100" title="状态">
          <!-- 状态 -->
          <template #cell="{ record }">
            <a-typography-text v-if="record.state === 1" style="color: #999999">
              待处理
            </a-typography-text>
            <a-typography-text v-if="record.state === 2" type="primary">
              处理中
            </a-typography-text>
            <a-typography-text v-if="record.state === 3" type="success">
              已完成
            </a-typography-text>
          </template>
        </a-table-column>
      </tableTurn>
    </div>
  </a-modal>

  <AddTask
    v-model:visible="isTaskVisible"
    :tableData="taskTableData"
    v-if="taskTableData.length > 0"
    @reject="reject"
  >
  </AddTask>
  <SelectSupplier
    v-model:visible="supplierVisible"
    :supplierNumber="supplierNumber"
    v-if="supplierVisible"
    @handleSupplierOk="handleSupplierOk"
  ></SelectSupplier>
  <a-modal
    v-model:visible="isSupplierVisible"
    @ok="splitHandleOk"
    @cancel="handleCancel"
  >
    <template #title> 拆分数量 </template>
    <div
      >拆分数量：<a-input-number
        :min="1"
        :style="{ width: '320px' }"
        v-model="splitAmount"
        :max="copyRecord.amount"
    /></div>
  </a-modal>
  <AddOrder
    v-model:visible="modelVisible"
    :SeeDate="SeeDate"
    :type="setupType"
  ></AddOrder>
</template>

<script lang="ts" setup>
  import {
    reactive,
    ref,
    onMounted,
    computed,
    watch,
    defineAsyncComponent,
  } from 'vue';
  import mitter from '@/utils/mitt';
  import dayjs from 'dayjs';
  import { getPurchaseProductList } from '@/api/buy-management/buy-material/index';
  import {
    postPlanPurchase,
    delPlanPurchase,
    putPlanPurchase,
  } from '@/api/buy-management/buy-plan/index';
  import { cloneDeep } from 'lodash';
  import { useRouter } from 'vue-router';
  import { Message } from '@arco-design/web-vue';
  import { useBuyStore } from '@/store';
  import { dispose } from 'echarts';
  import { getPurchaseProductNumber } from '@/api/buy-management/buy-material/index';
  // import SelectSupplier from './components/select-supplier.vue';
  import AddOrder from './components/add-order.vue';

  const store = useBuyStore();
  let AddTask = defineAsyncComponent(
    () => import('./components/add-buy-task.vue')
  );
  const router = useRouter();
  const splitAmount = ref();
  const isTaskVisible = ref(false);
  const tableRefs = ref();
  const taskTableData = ref([]);
  const emit = defineEmits(['update:oneValue', 'handleSupplierOk']);
  const props = withDefaults(
    defineProps<{
      props: { [propName: string]: any };
      name?: string;
      required?: boolean;
      values: any;
      disabled: boolean;
      regex?: {
        [name: string]: {
          role: any;
          name: any;
        };
      };
    }>(),
    {}
  );

  console.log('09', props);

  // 选择器配置
  const args = reactive({
    rowSelection: {
      type: 'checkbox',
      showCheckedAll: true,
      onlyCurrent: false,
    },
  });

  interface ParamsType {
    pageIndex: number;
    pageSize: number;
    number: string;
    clientCompanyName: string;
    status: number[];
    startTime: string;
    endTime: string;
  }
  const demandListParams = reactive<ParamsType>({
    pageIndex: 0,
    pageSize: 10,
    number: '',
    clientCompanyName: '',
    status: [],
    startTime: '',
    endTime: '',
  });
  let tableRef = ref();
  const supplierVisible = ref(false);
  const selectedKeys = ref([]);
  let modalVisible = ref(false);
  let currType = ref(''); // 判断是新增主分类还是子分类
  const currForm = reactive({
    list: {},
  });

  let data = ref([]);
  // 选择器配置

  let rowSelection = {
    type: 'checkbox',
    showCheckedAll: true,
    onlyCurrent: false,
  };

  const selectedList = ref([]);
  const modelVisible = ref(false);
  const SeeDate = ref();
  const setupType = ref();
  const See = (item: any) => {
    console.log(1, item);
    store.CreateOrder = {
      Product: [{ ...item, planProductId: item.id }],
    };
    router.push({
      name: 'AddOrderPurchaseList',
    });
    // modelVisible.value = true;
    // SeeDate.value = [{ ...item }];
    // setupType.value = 1;
  };
  // 选择数据事件
  const onSelect = (rowKeys: any, rowKey: any, record: any) => {
    const index = selectedList.value.findIndex((item: any) => {
      return item.id === rowKey;
    });
    if (index === -1) {
      selectedList.value.push(record);
      selectedKeys.value.push(record.id);
    } else {
      selectedList.value.splice(index, 1);
    }
  };

  // 全选按钮
  const onSelectAll = (checked: boolean) => {
    if (checked) {
      selectedList.value = cloneDeep(data.value);
    } else {
      selectedList.value = [];
    }
  };

  let numberVal = ref(''); // 物料编码搜索值
  let nameVal = ref(''); // 物料编码搜索值

  const getPlanData = () => {
    data.value = props.props.data || [];
    data.value.forEach((item) => {
      if (item.state !== 1) item.disabled = true;
    });
  };
  getPlanData();
  // 获取物料列表数据
  const getMaterialData = async (pageData?: any) => {
    try {
      let data = {};
      if (numberVal.value) data.number = numberVal.value;
      if (nameVal.value) data.name = nameVal.value;
      const res = await getPurchaseProductList({
        ...pageData,
        ...data,
        state: 1,
      });
      for (let i = 0; i < props.props.addIds.length; i += 1) {
        const obj1 = props.props.addIds[i];
        const matchingObjIndex = res.content.findIndex(
          (obj2: any) => obj2.id === obj1
        );
        if (matchingObjIndex !== -1) {
          res.content[matchingObjIndex].disabled = true;
        }
      }
      return Promise.resolve(res);
    } catch (error: unknown) {
      console.log(error);
    }
  };

  const selectData = ref<any>([]); // 选中的数据

  const visible = ref(false);

  const addTd = () => {
    visible.value = true;
  };
  const del = (key: any) => {
    selectData.value.splice(key, 1);
  };

  // 点击搜索按钮
  const search = () => {
    tableRef.value.loadData();
  };

  // 点击重置按钮
  const reset = () => {
    numberVal.value = '';
    nameVal.value = '';
    tableRef.value.params = {
      // 分页数据，用于请求
      page: 1,
      size: 10,
    };
    tableRef.value.loadData();
  };

  // 监听键盘回车，按了回车也会查询
  const keyDown = (e: any) => {
    if (e.keyCode === 13) {
      tableRef.value.loadData();
    }
  };

  onMounted(() => {
    window.addEventListener('keydown', keyDown); // 监听键盘事件
  });

  // 修改销售数量
  const guidePriceChange = (record?: any) => {
    if (record.guidePrice !== undefined && record.amount !== undefined)
      record.totalPrice = record.guidePrice * record.amount;
    else record.totalPrice = 0;
    mitter.emit('materialAmountRefresh', record);
  };

  const cgeDiscount = async (record: any) => {
    if (record.discount) {
      let msg = ref(0);
      msg.value = (100 - record.discount) / 100;
      const newMsg = record.guidePrice * record.amount;
      record.totalPrice = newMsg * msg.value;
      record.planNumber = props.props.number;
      // await putPlanPurchase({ ...record });
    } else {
      guidePriceChange(record);
    }
  };

  const cgePlanAmount = async (record: any) => {
    if (record.guidePrice !== undefined && record.amount !== undefined)
      record.totalPrice = record.guidePrice * record.amount;
    else record.totalPrice = 0;
    record.discount = 0;
    mitter.emit('materialAmountRefresh', record);
    // await putPlanPurchase({ ...record });
  };

  // 修改销售单价单位
  const saleUnitChange = (record: any) => {
    // 销售单价的单位和合计总价的单位同步
    record.total.unit = record.salesPrice.unit;
  };

  const delItem = async (res: any, rowIndex) => {
    if (res.isRenew === 1) {
      const index = props.props.addIds.indexOf(res.id);
      props.props.addIds.splice(index, 1);
    } else if (res.isRenew === 2) {
      props.props.deleteIds.push(res.id);
      res.RenewId.forEach((ele) => {
        props.props.addIds.splice(props.props.addIds.indexOf(ele), 1);
      });
    } else if (!res.isRenew) {
      props.props.deleteIds.push(res.id);
    } else if (res.isRenew === 3) {
      res.RenewId.forEach((ele) => {
        // const index = props.props.addIds.indexOf(ele);
        props.props.addIds.splice(props.props.addIds.indexOf(ele), 1);
      });
    }
    props.props.data.splice(rowIndex, 1);
  };

  const CgePriceUnit = async (e: any, key: string, record: any) => {
    record.key = e;
    // await putPlanPurchase({ ...record });
  };

  const handleOk = async () => {
    // if (props.props.data === null) props.props.data = [];
    for (const item of tableRef.value.selectedList) {
      const index = props.props.data?.findIndex(
        (ele) => ele.number === item.number
      );
      if (index === -1) {
        item.sid = `${item.id}`;
        props.props.addIds.push(item.id);
        item.isRenew = 1;
        item.RenewId = [];
        item.RenewId.push(item.id);
        props.props.data.push({ ...item });
      } else {
        props.props.data[index].isRenew = 2;
        props.props.data[index].RenewId = props.props.data[index].RenewId || [];
        if (props.props.data[index].RenewId.length > 0)
          props.props.data[index].isRenew = 3;
        props.props.data[index].RenewId.push(item.id);
        props.props.addIds.push(item.id);
        const msg = props.props.data[index].sid.split('-');
        const CapplyNumber = props.props.data[index].applyNumber.split(',');
        msg.push(item.id);
        CapplyNumber.push(item.applyNumber);
        props.props.data[index].sid = msg.join('-');
        props.props.data[index].sourceProductId = item.id;
        props.props.data[index].applyNumber = CapplyNumber.join(',');
        props.props.data[index].amount += item.amount;
      }
    }
    tableRef.value.selectedList = [];
    tableRef.value.selectedKeys = [];
  };

  // 新增分类弹出框
  const add = () => {
    modalVisible.value = true;
  };

  // 获取数据

  const rowIndex = ref();
  const supplierNumber = ref();
  const cgeSupplier = (number, Ind) => {
    rowIndex.value = Ind;
    supplierVisible.value = true;
    supplierNumber.value = number;
    // getData(number);
  };

  const handleSupplierOk = async (SelectDate) => {
    props.props.data.forEach((item, index) => {
      if (rowIndex.value === index) {
        item.guidePriceUnit = SelectDate[0].singleUint;
        item.guidePrice = SelectDate[0].singlePrice;
        item.supplierId = SelectDate[0].supplierId;
        item.supplierName = SelectDate[0].supplierName;
        item.totalPrice = SelectDate[0].singlePrice * item.amount;
        item.discount = 0;
      }
    });
    props.props.data[rowIndex.value].planNumber = props.props.number;
    // tableRefs.value.loadData();
    // await putPlanPurchase({ ...props.props.data[rowIndex.value] });
    getPlanData();
  };

  // 创建单条采购任务
  const buildSingleTask = (record: any) => {
    isTaskVisible.value = true;
    record.planProductId = record.id;
    delete record.id;
    taskTableData.value[0] = { ...record };
  };

  // 创建单条采购订单
  // const buildSingleOrder = (record: any) => {
  //   const { supplierId, supplierName, totalPrice } = record;
  //   store.CreateOrder = {
  //     supplierId,
  //     supplierName,
  //     totalPrice,
  //     Product: [{ ...record, planProductId: record.id }],
  //   };
  //   delete record.id;
  //   if (sessionStorage.getItem('store')) {
  //     sessionStorage.removeItem('store');
  //   }
  //   router.push({
  //     name: 'AddOrderPurchaseList',
  //   });
  // };

  // const isBatchBuildTask = () => {
  //   return data.value.every((ele) => ele.state > 1);
  // };

  // const isBatchBuildOrder = () => {
  //   return data.value.every((ele) => ele.state > 1);
  // };

  const batchBuildOrder = () => {
    let Product = ref(selectedList.value.filter((item) => !item.disabled));
    Product.value.forEach((item) => {
      item.planProductId = item.id;
      delete item.id;
    });
    store.CreateOrder = {
      Product: Product.value,
    };
    router.push({
      name: 'AddOrderPurchaseList',
    });
    // modelVisible.value = true;

    // SeeDate.value = selectedList.value.filter((item) => !item.disabled);
    // setupType.value = 2;
  };

  const batchBuildTask = () => {
    taskTableData.value = selectedList.value;
    taskTableData.value.forEach((i: any) => {
      i.planProductId = i.id;
    });
    isTaskVisible.value = true;
  };

  const reject = () => {
    taskTableData.value = [];
    selectedList.value = [];
    selectedKeys.value = [];
  };

  const copyRecordData = ref([]);
  const isSupplierVisible = ref(false);
  const copyRecord = ref({ amount: 0 });
  // 获取数据
  // const getData = async (number: any) => {
  //   const res = await getPurchaseProductNumber({ number });
  //   copyRecordData.value = res;
  // };

  const addNewProduct = (record: any) => {
    isSupplierVisible.value = true;
    copyRecord.value = record;
    splitAmount.value = 0;
    // getData(record.number);
  };

  const splitHandleOk = () => {
    let msg = cloneDeep(copyRecord.value);
    msg.amount = splitAmount.value;
    delete msg.id;
    props.props.data.push({ ...msg });
    copyRecord.value.amount -= splitAmount.value;
    guidePriceChange(copyRecord.value);
    isSupplierVisible.value = false;
  };

  const searchHandleCancel = () => {
    visible.value = false;
    tableRef.value.selectedList = [];
    tableRef.value.selectedKeys = [];
  };
</script>

<style scoped lang="less">
  .container {
    margin-bottom: 20px;

    .content {
      // padding: 20px 20px;
    }
    .state-item {
      position: relative;
      left: 50%;
      transform: translateX(-50%);
    }
    .state-item-Y {
      width: 30px;
      height: 30px;
      font-size: 12px;
      border: 1px solid rgba(148, 191, 255, 1);
      background-color: rgba(232, 243, 255, 1);
      border-radius: 5px;
      display: flex;
      align-items: center;
      justify-content: center;
      color: #3d7eff;
    }
    .state-item-N {
      color: #f53f3f;
      width: 30px;
      height: 30px;
      font-size: 12px;
      border: 1px solid rgba(251, 172, 163, 1);
      background-color: rgba(255, 236, 232, 1);
      border-radius: 5px;
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }

  :deep(.arco-select-view-single) {
    padding-right: 6px;
    padding-left: 6px;
  }

  :deep(.select-view-single),
  :deep(.arco-select-view-size-medium),
  :deep(.arco-select-view-value) {
    font-size: 1px;
    .arco-select-view-value {
      font-size: 1px;
    }
  }

  :deep(.arco-table-tr) {
    height: 40px;
  }
  :deep(.arco-table-th) {
    font-weight: bold;
  }
</style>
